package com.central.scheduler.plugin.task.sql;

import com.central.common.enums.DataType;
import com.central.common.model.DatasourceInfo;
import com.central.common.model.ResourceInfo;
import com.central.common.properties.Property;
import com.central.scheduler.spi.task.AbstractParameters;
import com.central.scheduler.spi.utils.JSONUtils;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author Tindy
 * @date 2021/12/23
 * @describe
 * Sql/Hql parameter
 */
@Setter
@Getter
public class SqlParameters extends AbstractParameters {


    /**
     * datasource
     */
    private DatasourceInfo datasource;

    /**
     * sql
     */
    private String sql;



    @Override
    public boolean checkParameters() {
        return datasource != null && StringUtils.isNotEmpty(sql);
    }

    @Override
    public List<ResourceInfo> getResourceFilesList() {
        return new ArrayList<>();
    }

    @Override
    public void dealOutParam(String result) {
        if (CollectionUtils.isEmpty(localParams)) {
            return;
        }
        List<Property> outProperty = getOutProperty(localParams);
        if (CollectionUtils.isEmpty(outProperty)) {
            return;
        }
        if (StringUtils.isEmpty(result)) {
            varPool.addAll(outProperty);
            return;
        }
        List<Map<String, String>> sqlResult = getListMapByString(result);
        if (CollectionUtils.isEmpty(sqlResult)) {
            return;
        }
        //if sql return more than one line
        if (sqlResult.size() > 1) {
            Map<String, List<String>> sqlResultFormat = new HashMap<>();
            //init sqlResultFormat
            Set<String> keySet = sqlResult.get(0).keySet();
            for (String key : keySet) {
                sqlResultFormat.put(key, new ArrayList<>());
            }
            for (Map<String, String> info : sqlResult) {
                for (String key : info.keySet()) {
                    sqlResultFormat.get(key).add(String.valueOf(info.get(key)));
                }
            }
            for (Property info : outProperty) {
                if (info.getType() == DataType.LIST) {
                    info.setValue(JSONUtils.toJsonString(sqlResultFormat.get(info.getProp())));
                    varPool.add(info);
                }
            }
        } else {
            //result only one line
            Map<String, String> firstRow = sqlResult.get(0);
            for (Property info : outProperty) {
                info.setValue(String.valueOf(firstRow.get(info.getProp())));
                varPool.add(info);
            }
        }

    }

}
